package com.site.common.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Title: RSAUtils
 * @Author LinLuoChen
 * @ProjectName wx
 * @Description: RSAUtils 加密方法
 * @Date 2023/8/30 16:02
 */
public class RSAUtils {
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    private static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKYHzNyxgRuX1ij66kO483bLX77/B4" +
            "n69mEFLwvYf8cc8bWropY9XvM6sLsSFnp0cHREar2tPKJlv5vUArN/Gyp/mk6YE6grfoRqFTSENH3MNUo9t8ZpYu4RtWWXIxDfb6eVBHEL" +
            "fPbjnVzBAgCcqbsWxssePuqBciMgqBNWIwMZAgMBAAECgYAYm/tfkufiISVbOaXTl+xuZUKx2rdRWmN+ifgpN1PpPX8OQHx+7GXQg5iCg" +
            "fHXAL9SXHm915mvMImwHUKxPFvYOQoWoXpxgP9f1ElB5riSAzice220md0n4hZ6A8Xmg6QpMA43H0weDceAqAMmdRuimPxPhZ/APYqnjc8j" +
            "lRqqCQJBAO2VZzsofKGSiQNvnrLVbMpWxbuztaRiedl+wlGswCnNZSp/8X9lBuX7r2bsfCepHk9+ia+NiWSqL2iqiLlemrsCQQCy5oARXE6a" +
            "m17ebBOUD2f65TgiPdUCuoSULazAiUhJ1E9FX+NjUWfZpOF+CR5onRvJeNamG4ki0Z8O8Hxte247AkBKADgoQAMZ3Geaz2CR+VIqb/6k6WPR" +
            "cO7dJNNn1zP/kT9KjpFtCc2tQsiueUhungmX3yUJrj82QKAFrOBrRKFTAkB9+RlNIDapX6aZ8HiI1aBeZ3Hzip6n4TbiMJdorEKe2kVHkJH" +
            "JqdT6yMOPwFQNTjP21oQvS0xxnDHojybO4Q9pAkEAuSPwBYjoZIRQLxLangXW0s1gFPD+H6xmc1Qk0tdQHVaW3v5E81UX8MdlOahtbEibF1x" +
            "7StTjfCtSMn7ZbaxsGQ==";

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data      待加密数据
     * @return
     */
    public static String encrypt(String data,String publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data       待解密数据
     * @return
     */
    public static String decrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, RSAUtils.getPrivateKey(privateKey));
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 签名
     *
     * @param data       待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * 验签
     *
     * @param srcData   原始字符串
     * @param publicKey 公钥
     * @param sign      签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    public static void main(String[] args) {
        try {
            // 生成密钥对
//            KeyPair keyPair = getKeyPair();
//            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
//            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            String publieKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmB8zcsYEbl9Yo+upDuPN2y1++/weJ+vZhBS8L2H/H" +
                    "HPG1q6KWPV7zOrC7EhZ6dHB0RGq9rTyiZb+b1AKzfxsqf5pOmBOoK36EahU0hDR9zDVKPbfGaWLuEbVllyMQ32+nlQRxC3z2451cwQIAnKm" +
                    "7FsbLHj7qgXIjIKgTViMDGQIDAQAB";
            System.out.println("私钥:" + privateKey);
            System.out.println("公钥:" + publieKey);
            // RSA加密
            JSONArray data = new JSONArray();
            JSONObject ds2 = new JSONObject();
            ds2.put("deviceSn","字符");
            ds2.put("deviceId","11111111");
            ds2.put("deviceAuthCode","字符");
            ds2.put("monitorDateTime","2023-10-09 13:28:26");
            ds2.put("name","字符");
            ds2.put("idNo","3723241999010112345");
            ds2.put("multiple","字符");
            ds2.put("moment","字符");
            ds2.put("weight","字符");
            ds2.put("windSpeed","字符");
            ds2.put("windLevel","字符");
            ds2.put("rrange","字符");
            ds2.put("height","字符");
            ds2.put("angle","字符");
            ds2.put("obliguity","字符");
            data.add(ds2);
//            String data = "test";
            String encryptData = encrypt(data.toString(),publieKey);
            System.out.println("加密后内容:" + encryptData);
            String decryptData = decrypt(encryptData);
            System.out.println("解密后内容:" + decryptData);
            // RSA签名
            String sign = sign(encryptData, getPrivateKey(privateKey));
            System.out.println("sign 签名："+sign);
            // RSA验签
            boolean result = verify(encryptData, getPublicKey(publieKey), sign);
            System.out.print("验签结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("加解密异常");
        }
    }
}
